package com.jumper.study.admin.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jumper.study.admin.dto.req.AdminCreateGroup;
import com.jumper.study.admin.dto.req.AdminReq;
import com.jumper.study.admin.dto.resp.AccountResp;
import com.jumper.study.admin.dto.resp.AdminResp;
import com.jumper.study.admin.service.AccountService;
import com.jumper.study.admin.service.AdminService;
import com.jumper.study.common.api.CommonResult;
import com.jumper.study.common.api.ResultCode;
import com.jumper.study.db.model.Account;
import com.jumper.study.db.model.Admin;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;




@RestController
@RequestMapping("/api/backend/admins")
public class AdminController {
    private static final Logger LOGGER = LoggerFactory.getLogger(AdminController.class);

    @Value("${study-setting.admin.id:1}")
    private Integer ADMIN_ID;

    @Autowired
    private AdminService adminService;

    @Autowired
    private AccountService accountService;

    @GetMapping("")
    public CommonResult<List<AdminResp>> getList() {
        List<Admin> adminList = adminService.getWithAccountList();
        List<AdminResp> respList = adminList.stream()
                    .map(m -> {
                        LOGGER.info("管理员:{}", m);
                        return new AdminResp(m.getId(), m.getAccountId(), m.getRoleId(), m.getMenus(), m.getDisabled(),
                            new AccountResp(m.getAccountId(), m.getAccount().getUsername(), m.getAccount().getName(),
                            m.getAccount().getAvatar(), m.getAccount().getUpdatedAt())
                        );
                    }).toList();

        return CommonResult.success(respList);
    }
    
    @GetMapping("/{id}")
    public CommonResult<AdminResp> getItem(@PathVariable Integer id) {
        Admin admin = adminService.getById(id);
        if (admin == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getMessage());
        }
        AdminResp resp = new AdminResp();
        resp.setId(admin.getId());
        resp.setAccountId(admin.getAccountId());
        resp.setRoleId(admin.getRoleId());
        resp.setMenus(admin.getMenus());
        resp.setDisabled(admin.getDisabled());

        Account account = accountService.getById(admin.getAccountId());
        if (account != null) {
            resp.setAccount(new AccountResp(account.getId(), account.getUsername(), account.getName(), account.getAvatar(), account.getUpdatedAt()));
        }
        
        return CommonResult.success(resp);
    }
    
    @PostMapping("/")
    public CommonResult<Boolean> create(@RequestBody @Validated(value={AdminCreateGroup.class}) AdminReq req) {
        Admin entity = adminService.getByAccountId(req.getAccountId());
        if (entity != null) {
            return CommonResult.success(true);
        }
        entity = new Admin();
        entity.setAccountId(req.getAccountId());
        entity.setRoleId(req.getRoleId());
        entity.setMenus(req.getMenus());
        boolean result = adminService.save(entity);

        return CommonResult.success(result);
    }
    
    @PostMapping("/{id}")
    public CommonResult<Boolean> update(@PathVariable Integer id, @RequestBody @Validated AdminReq req) {
        Admin admin = adminService.getById(id);
        if (admin == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getMessage());
        }
        admin.setRoleId(req.getRoleId());
        admin.setMenus(req.getMenus());

        boolean result = adminService.updateById(admin);
        return CommonResult.success(result);
    }
    
    @PostMapping("/{id}/status")
    public CommonResult<Boolean> updateStatus(@PathVariable Integer id) {
        Admin admin = adminService.getById(id);
        if (admin == null) {
            return CommonResult.notFound();
        }

        if (ADMIN_ID == id) {
            return CommonResult.failed("不能禁用管理员账号");
        }

        boolean result = adminService.disableById(admin);

        return CommonResult.success(result);
    }
    
}
